package com.example.sftpclient

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*

class RemoteFileAdapter(
    private var files: List<RemoteFile>,
    private val onItemClick: (RemoteFile) -> Unit,
    private val onItemLongClick: (RemoteFile) -> Boolean
) : RecyclerView.Adapter<RemoteFileAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val fileIcon: ImageView = view.findViewById(R.id.fileIcon)
        val fileName: TextView = view.findViewById(R.id.fileName)
        val fileInfo: TextView = view.findViewById(R.id.fileInfo)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_remote_file, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val file = files[position]
        holder.fileName.text = file.name
        
        // 设置图标
        holder.fileIcon.setImageResource(
            if (file.isDirectory) android.R.drawable.ic_menu_more
            else android.R.drawable.ic_menu_save
        )

        // 格式化文件信息
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val dateStr = sdf.format(Date(file.modifyTime))
        val sizeStr = if (file.isDirectory) "目录" else formatFileSize(file.size)
        holder.fileInfo.text = "$dateStr  $sizeStr"

        // 设置点击事件
        holder.itemView.setOnClickListener { onItemClick(file) }
        holder.itemView.setOnLongClickListener { onItemLongClick(file) }
    }

    override fun getItemCount() = files.size

    fun updateFiles(newFiles: List<RemoteFile>) {
        files = newFiles
        notifyDataSetChanged()
    }

    private fun formatFileSize(size: Long): String {
        return when {
            size < 1024 -> "$size B"
            size < 1024 * 1024 -> "${size / 1024} KB"
            size < 1024 * 1024 * 1024 -> "${size / (1024 * 1024)} MB"
            else -> "${size / (1024 * 1024 * 1024)} GB"
        }
    }
} 